package com.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.entity.Result;
import com.entity.Verify;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

//获取验证码controller
@RestController
@RequestMapping("/verifyCode")
public class VerifyCodeController {
    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping("/create")
    public Result create(HttpServletResponse response){
        //生成随机4位验证码
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100, 4, 6);
        String code = lineCaptcha.getImageBase64Data();

        //生成一个uuid
        String uuid = UUID.randomUUID().toString().replace("-", "");

        //将验证码存入redis，并且设置2分钟过期时长
        redisTemplate.opsForValue().set("code:"+uuid, lineCaptcha.getCode(), 2, TimeUnit.MINUTES);

        return Result.ok(new Verify(uuid, code));
    }
}
